package cn.edu.ustc.brainor.ustcgate;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.Nullable;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 欧伟科 on 2016/10/14.
 * 用来完成GPS和中科大网关两个服务
 */

public class LocationService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Looper mServiceLooper;
    private ServiceHandler mServiceHandler;

    LocationAcquire locationAcquire = LocationAcquire.getmInstance(this);


    // Handler that receives messages from the thread
    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg2) {
                case ConnectivityManager.TYPE_MOBILE:
                    locationAcquire.startLocationChangeListenner();
                    break;
                case ConnectivityManager.TYPE_WIFI:
                    locationAcquire.stopLocationChangeListener();
                    break;
            }
            // Stop the service using the startId, so that we don't stop
            // the service in the middle of handling another job
//            stopSelf(msg.arg1);
        }
    }

    @Override
    public void onCreate() {
        //注册网络变化的broadcast
        IntentFilter filterInService = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        filterInService.addAction("my_action_strings");//以后增加
        registerReceiver(receiverInService, filterInService);
        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.  We also make it
        // background priority so CPU-intensive work will not disrupt our UI.
        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();

        // Get the HandlerThread's Looper and use it for our Handler
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    /**
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
        //设置一个broadcast receiver?
        usteTask();//中科大网关服务
        locationTask();//GPS定位服务
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        switch (intent.getStringExtra(locationAcquire.context.getPackageName() + ".ConnectStat").toLowerCase()) {

            case "mobile":
                msg.arg2 = ConnectivityManager.TYPE_MOBILE;
                mServiceHandler.sendMessage(msg);
                break;
            case "wifi":
            case "null":
                msg.arg2 = ConnectivityManager.TYPE_WIFI;
                mServiceHandler.sendMessage(msg);
                break;
        }
        // For each start request, send a message to start a job and deliver the
        // start ID so we know which request we're stopping when we finish the job


        // If we get killed, after returning from here, restart
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
    }

    public class ServiceBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

        }
    }

    private void usteTask() {
        NetworkInfo netInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (netInfo != null && netInfo.isAvailable()) {
            String name = netInfo.getTypeName();
            if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {

//                Toast.makeText(LocationService.this, "WIFI", Toast.LENGTH_SHORT).show();
                if (true) {//有WiFi情况下判断是否连上中科大网络
                    new AsyncTask<String, Void, String>() {
                        @Override
                        protected String doInBackground(String... webHTMLs) {
                            return new NetworkConnect().连接网络通();
                        }

                        @Override
                        protected void onPostExecute(String htmlText) {
                            Matcher matcher = Pattern.compile("(?<=信息：)[\\s\\S]+?(?=</td>)").matcher(htmlText);
                            if (matcher.find()) {
                                String 信息 = matcher.group();
                                Toast.makeText(LocationService.this, 信息.replaceAll("<[\\s\\S]+?>", ""), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }.execute();
                }
            }
        }
    }

    private void locationTask() {

    }

    private final BroadcastReceiver receiverInService = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();
            if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION)){
                NetworkInfo netInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable()) {

                }
                usteTask();
                locationTask();
            }
        }
    };
}
